﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Configuration;
using System.IO;

namespace LongNet.Util
{    
    public static class HttpUtil
    {
        private static LogManager.Logger logger = LogManager.GetCurrentClassLogger();      

        #region Properties
        #endregion

        #region Constructor
        #endregion

        #region Methods

        #region GetAppSettings

        /// <summary>
        /// Gets the value by key in AppSettings node which is set in the web.config file.
        /// </summary>
        /// <param name="key">The key to look for.</param>
        /// <param name="required">Set to true if the value is required.</param>
        /// <param name="allowEmpty">Set to true if the value can not be empty string.</param>
        /// <returns>The string value related to the key.</returns>
        public static string GetAppSettings(string key, bool required, bool allowEmpty)
        {
            var msg = string.Empty;
            var value = ConfigurationManager.AppSettings[key];

            if (required && value == null)
            {
                msg = string.Format("AppSettings for key {0} is not set.", key);



                throw new Exception(msg);
            }

            if (!allowEmpty && value == string.Empty)
            {
                msg = string.Format("AppSettings for key {0} is set but empty.", key);



                throw new Exception(msg);
            }

            return value ?? string.Empty;
        }

        #endregion
        #region HttpGet/HttpGet

        /// <summary>
        /// Executes a http web request using "Get" method and returns the responsed string.
        /// </summary>
        /// <param name="url">The url to request.</param>
        /// <returns>The responsed string.</returns>
        public static string HttpGet(string url)
        {  
            string fileName="";
            return HttpGet(url, "utf-8", null, null, false, out fileName);
        }

        /// <summary>
        /// Executes a http web request using "Get" method and returns the responsed string.
        /// </summary>
        /// <param name="url">The url to request.</param>
        /// <returns>The responsed string.</returns>
        public static string HttpGet(string url, string domain,bool isSave,out string fileName)
        {
            return HttpGet(url, "utf-8", null, domain, isSave, out fileName);
        }

        /// <summary>
        /// Executes a http web request using "Get" method and returns the responsed string.
        /// </summary>
        /// <param name="url">The url to request.</param>
        /// <param name="encodingName">The encoding name.</param>
        /// <param name="referer">The referer url or let it empty.</param>
        /// <returns>The responsed string.</returns>
        public static string HttpGet(string url, string encodingName, string referer, string domain, bool isSave, out string fileName)
        {
            fileName = "";
            try
            {
                var request = (HttpWebRequest)HttpWebRequest.Create(url);

                request.AllowAutoRedirect = true;
                request.Timeout = 36000;
                request.Method = "GET";
                request.Headers["Cache-Control"] = "no-cache";
                request.Accept = "*/*";
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506; .NET CLR 3.5.21022)";

                if (!string.IsNullOrEmpty(referer))
                {
                    request.Referer = referer;
                }

                Encoding encoding = Encoding.GetEncoding(encodingName);

                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    var stream = response.GetResponseStream();                   
                    if (logger.IsDebugEnabled)
                        logger.Debug("HttpPost({0}) response.StatusCode is:{1} {2}", url, response.StatusCode, (int)response.StatusCode);

                    using (var reader = new StreamReader(stream, encoding))
                    {
                        string content = reader.ReadToEnd();
                        //是否保存
                        if (isSave)
                        {

                            int hostindex = request.RequestUri.ToString().IndexOf(request.RequestUri.Host);
                            string httpRegex = @"(h|H)(t|T)(t|T)(p|P)://" + request.RequestUri.Host + "/";
                            int urllength = request.RequestUri.ToString().Length;
                            string rawUrl = request.RequestUri.ToString().Substring(hostindex + request.RequestUri.Host.Length, urllength - hostindex - request.RequestUri.Host.Length);
                            if (string.IsNullOrEmpty(domain))
                            {
                                domain = request.RequestUri.Host;
                            }
                            fileName = GetAppSettings("LongNet.DownLoadFolder", false, true) + "\\" + domain + "\\" + rawUrl.Replace("/", "\\").Split('?')[0];
                            //if(!File.Exists(fileName))
                            LongNet.IO.FileManager.SaveFile(Regex.Replace(content,httpRegex,"~\\"), fileName, false);

                        }
                        return content;
                    }
                }
            }
            catch (Exception ex)
            {
                if (logger.IsErrorEnabled)
                    logger.Error(ex, "HttpGet({0})", url);

                return ex.Message;
            }
        }

        /// <summary>
        /// Executes a http web request using "Post" method and returns the responsed string.
        /// </summary>
        /// <param name="url">The url to request.</param>
        /// <param name="postData">The data to be post.</param>
        /// <returns>The responsed string.</returns>
        public static string HttpPost(string url, string postData)
        {
            return HttpPost(url, postData, "utf-8", null);
        }

        /// <summary>
        /// Executes a http web request using "Post" method and returns the responsed string.
        /// </summary>
        /// <param name="url">The url to request.</param>
        /// <param name="postData">The data to be post.</param>
        /// <param name="encodingName">The encoding name.</param>
        /// <param name="referer">The referer url or let it empty.</param>
        /// <returns>The responsed string.</returns>
        public static string HttpPost(string url, string postData, string encodingName, string referer)
        {
            try
            {
                var request = (HttpWebRequest)HttpWebRequest.Create(url);

                var encoding = Encoding.GetEncoding(encodingName);
                var dataBytes = encoding.GetBytes(postData ?? string.Empty);

                request.AllowAutoRedirect = true;
                request.Timeout = 36000;
                request.Method = "POST";
                request.Headers["Cache-Control"] = "no-cache";
                request.Accept = "*/*";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = dataBytes.Length;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506; .NET CLR 3.5.21022)";

                if (!string.IsNullOrEmpty(referer))
                {
                    request.Referer = referer;
                }

                using (var stream = request.GetRequestStream())
                {
                    stream.Write(dataBytes, 0, dataBytes.Length);
                    stream.Close();
                }

                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    var stream = response.GetResponseStream();

                    if (logger.IsDebugEnabled)
                        logger.Debug("HttpPost({0}) response.StatusCode is:{1} {2}", url, response.StatusCode, (int)response.StatusCode);

                    using (var reader = new StreamReader(stream, encoding))
                    {
                        string content = reader.ReadToEnd();

                        return content;
                    }
                }
            }
            catch (Exception ex)
            {
                if (logger.IsErrorEnabled)
                    logger.Error(ex, "HTTP请求失败，HttpGet({0})", url);

                return ex.Message;
            }
        }

        #endregion


        #region 下载保存图片
        /// <summary>
        /// Executes a http web request using "Get" method and returns the responsed string.
        /// </summary>
        /// <param name="url">The url to request.</param>
        /// <param name="encodingName">The encoding name.</param>
        /// <param name="referer">The referer url or let it empty.</param>
        /// <returns>The responsed string.</returns>
        public static void HttpGetImage(string url, string DirName)
        {
            try
            {
                var request = (HttpWebRequest)HttpWebRequest.Create(url);
                string ext = System.IO.Path.GetExtension(url);
                request.AllowAutoRedirect = true;
                request.Timeout = 3600;
                request.Method = "GET";
                request.Headers["Cache-Control"] = "no-cache";
                request.Accept = "*/*";
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506; .NET CLR 3.5.21022)";


                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    var stream = response.GetResponseStream();
                    System.Drawing.Image img;
                    img = System.Drawing.Image.FromStream(stream);
                    string filename = string.Empty;

                    if (!DirName.IsNullOrEmpty())
                        filename = DirName;
                    else
                        filename = GetAppSettings("LongNet.DownLoadFolder", false, false);
                    filename += string.Format(@"\{0}",DateTime.Now.ToString("yyyyMMddhhmm"));

                    if (!Directory.Exists(filename))
                        Directory.CreateDirectory(filename);

                    filename += @"\" + System.IO.Path.GetFileName(url);
                    img.Save(filename);
                    if (logger.IsDebugEnabled)
                        logger.Debug(string.Format("HttpGetImage:{0},{1}", url, filename));
                    //switch (ext.ToLower())
                    //{
                    //    case ".gif":
                    //        img.Save(filename, ImageFormat.Gif);
                    //        break;
                    //    case ".jpg":
                    //    case ".jpeg":
                    //        img.Save(filename, ImageFormat.Jpeg);
                    //        break;
                    //    case ".png":
                    //        img.Save(filename, ImageFormat.Png);
                    //        break;
                    //    case ".icon":
                    //        img.Save(filename, ImageFormat.Icon);
                    //        break;
                    //    case ".bmp":
                    //        img.Save(filename, ImageFormat.Bmp);
                    //        break;
                    //}
                    img.Dispose();

                }
            }
            catch (Exception ex)
            {
                if (logger.IsErrorEnabled)
                    logger.Error(string.Format("HttpGetImage:{0},{1}", url, ex.Message));
            }
        }


        /// <summary>
        /// Executes a http web request using "Get" method and returns the responsed string.
        /// </summary>
        /// <param name="url">The url to request.</param>
        /// <param name="encodingName">The encoding name.</param>
        /// <param name="referer">The referer url or let it empty.</param>
        /// <returns>The responsed string.</returns>
        public static void HttpGetImage(string url,string domain,bool flag, out string fileName)
        {
            fileName = "";
            try
            {
                var request = (HttpWebRequest)HttpWebRequest.Create(url);
                string ext = System.IO.Path.GetExtension(url);
                request.AllowAutoRedirect = true;
                request.Timeout = 3600;
                request.Method = "GET";
                request.Headers["Cache-Control"] = "no-cache";
                request.Accept = "*/*";
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506; .NET CLR 3.5.21022)";


                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    var stream = response.GetResponseStream();
                    System.Drawing.Image img;
                    img = System.Drawing.Image.FromStream(stream);                  
                    int hostindex = request.RequestUri.ToString().IndexOf(request.RequestUri.Host);
                    string httpRegex = @"(h|H)(t|T)(t|T)(p|P)://" + request.RequestUri.Host + "/";
                    int urllength = request.RequestUri.ToString().Length;
                    string rawUrl = request.RequestUri.ToString().Substring(hostindex + request.RequestUri.Host.Length, urllength - hostindex - request.RequestUri.Host.Length);
                    fileName = GetAppSettings("LongNet.DownLoadFolder", false, true) + "\\" + domain+ "\\" + rawUrl.Replace("/", @"\").Split('?')[0];
                    fileName = fileName.Replace(@"\\", @"\");
                    if (!Directory.Exists(Path.GetDirectoryName(fileName)))
                        Directory.CreateDirectory(Path.GetDirectoryName(fileName));

                    //fileName += @"\" + System.IO.Path.GetFileName(url);
                    img.Save(fileName);
                    if (logger.IsDebugEnabled)
                        logger.Debug(string.Format("HttpGetImage:{0},{1}", url, fileName));
                    //switch (ext.ToLower())
                    //{
                    //    case ".gif":
                    //        img.Save(filename, ImageFormat.Gif);
                    //        break;
                    //    case ".jpg":
                    //    case ".jpeg":
                    //        img.Save(filename, ImageFormat.Jpeg);
                    //        break;
                    //    case ".png":
                    //        img.Save(filename, ImageFormat.Png);
                    //        break;
                    //    case ".icon":
                    //        img.Save(filename, ImageFormat.Icon);
                    //        break;
                    //    case ".bmp":
                    //        img.Save(filename, ImageFormat.Bmp);
                    //        break;
                    //}
                    img.Dispose();

                }
            }
            catch (Exception ex)
            {
                if (logger.IsErrorEnabled)
                    logger.Error(string.Format("HttpGetImage:{0},{1}", url, ex.Message));
            }
        }
        #endregion 下载保存图片
      

        #endregion
    }
}
